import { addList, delList, getList } from '@/http/func'
import { ListState } from '@/types/list'
import { Module } from 'vuex'
import { State } from '..'

export const list: Module<ListState, State> = {
	namespaced: true,
	state: {
		list: []
	},
	mutations: {
		SET_LIST(state, payload) {
			state.list = payload
		}
	},
	actions: {
		async getList({ commit }, payload) {
			const { data } = await getList(payload)
			data.sort((a, b) => a.zIndex - b.zIndex)
			commit('SET_LIST', data)
		},
		async addList({ state, commit }, payload) {
			const { data } = await addList(payload)
			const list = [].concat.call(state.list, data)
			commit('SET_LIST', list)
			return true
		},
		async delList({ state, commit }, payload) {
			try {
				await delList(payload)
				commit(
					'SET_LIST',
					state.list.filter((item) => item.id !== payload)
				)
			} catch (error) {
				console.log('error', error)
			}
		}
	}
}
